package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ShiroUserRealm extends AuthorizingRealm {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;
    /*定义ShiroUserRealm类，设置凭证匹配器（与用户添加操作相同的加密算法）*/
     @Override
     public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher){
         //构建凭证匹配对象
         HashedCredentialsMatcher cMatcher=new HashedCredentialsMatcher();
         //设置加密算法
         cMatcher.setHashAlgorithmName("MD5");
         //设置加密次数
         cMatcher.setHashIterations(1);
         super.setCredentialsMatcher(cMatcher);

     }
    /**
     * 通过此方法完成认证数据的获取及封装,系统 * 底层会将认证数据传递认证管理器，
     * 由认证 * 管理器完成认证操作。
     */
    //负责授权信息的获取和封装
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1获取登陆用户
        SysUser user=(SysUser)principalCollection.getPrimaryPrincipal();
        //2基于登陆用户查询用户对应的角色ID
        List<Integer> roleIds=sysUserRoleDao.findRoleIdsByUserId(user.getId());
        if(roleIds==null)
            throw new AuthenticationException();
        //3基于角色id查找菜单id并校验、、
        List<Integer> menuIds= sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
        return null;
    }
    //负责认证信息的获取和封装
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1获取登陆用户信息（用户名，密码）
        UsernamePasswordToken upToken=(UsernamePasswordToken)token;
        String username=upToken.getUsername();
        //2。基于用户名查询数据库中的用户对象
        SysUser user=sysUserDao.findUserByUserName(username);
        //3检测用户是否存在
        if(user==null)
            throw new UnknownAccountException();
        //4检测用户是否被禁用
        if(user.getValid()==0)
            throw new LockedAccountException();
        //5封装用户信息并返回
        ByteSource credentialsSalt=ByteSource.Util.bytes(user.getSalt());
       //，并加工一下加工为ByteSource类型
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(
                user,
                user.getPassword(),//Credentials,//凭证（密码）
                credentialsSalt,//byteSource,//盐值
                getName()//realname
        );
        return info;
    }
    /*设置加密算法*/
}
